package com.mt.roll.core.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;


/**
 * <p>
 *     微信解密工具类
 * </p>
 *
 * @author Mr.ZhangShi
 * @version 1.0
 * @date 2020/10/9
 */
public class WxDecodeUtil {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) throws Exception{
        String appId = "wxf7c523e6ffb6e7b4";
        String encryptedData = "j4mV+NynEPT4wmxqgNeF29b6CCz2DfBiXQzahJksc6yuDPn7W85h2zIV+SQFJR0u+EMJa37mncYgWl5uo0x9EHHZeq/5cYgNnI5LPtGbTyA8i+uk2wLhXYfZpAhX5ZDFDEX3svnXgU78PUlRHzqF+MAWcJjlP00V7IhKZGdESR8gyusY9JsINxKlbhrZOsFmFWzKOR8ZU9x8mlJmtIj2pw==";
        String sessionKey = "bNPKpLTmv2TgHViEGgyHOg==";
        String iv = "AUtk2XZB/6F8hTErDUeLGg==";
        String jsonStr = decrypt(appId, encryptedData, sessionKey, iv);

        System.out.println(jsonStr);
        String phoneNumber = com.alibaba.fastjson.JSONObject.parseObject(jsonStr).getString("phoneNumber");
        System.out.println(phoneNumber);
    }
}
